package apigateway.project.core.filter.loadbalance;

import apigateway.project.commen.config.ServiceInstance;
import apigateway.project.commen.exception.NotFoundException;
import apigateway.project.core.CacheConfig;
import apigateway.project.core.context.GlobalContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

import static apigateway.project.commen.enums.ResponseCode.SERVICE_INSTANCE_NOT_FOUND;

/**
 * 提供最小连接后端服务的负载均衡算法
 */
//很疑惑，不知道怎么看连接数
@Slf4j
public class LeastConnectionLoadBalanceRule implements LoadBalanceGatewayRule{
    @Override
    public ServiceInstance choose(GlobalContext ctx) {
        return choose(ctx.getRule().getServiceName());
    }

    @Override
    public ServiceInstance choose(String serviceName) {
        //获取服务实例集合
        Set<ServiceInstance> serviceInstanceSet = CacheConfig.getCacheConfig().getServiceByServiceName(serviceName);
        if (serviceInstanceSet.isEmpty()) {
            log.warn("No instance available for:{}", serviceName);
            throw new NotFoundException(SERVICE_INSTANCE_NOT_FOUND);
        }


        return null;
    }
}
